/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

package org.ponly.cta4j.service.store.ehcache;

import java.util.List;
import net.sf.ehcache.Element;
import org.ponly.cta4j.Captcha;
import org.ponly.cta4j.service.store.CaptchaStore;

/**
 * 基于 ehcache 实现的验证码存储, 默认使用名称为 {@link #DEFAULT_CACHE_NAME} 的缓存存放.
 *
 * @author vacoor
 * @since 1.0
 */
public class EhcacheStore implements CaptchaStore {
    /**
     * 默认缓存名称.
     */
    private static final String DEFAULT_CACHE_NAME = "cta4j.store.cache";

    /**
     * Cache.
     */
    private net.sf.ehcache.Cache cache;

    /**
     * 使用给定的 Ehcache CacheManager 创建 默认 EhcacheStore.
     *
     * @param cacheManager Ehcache CacheManager
     */
    public EhcacheStore(final net.sf.ehcache.CacheManager cacheManager) {
        this(cacheManager, DEFAULT_CACHE_NAME);
    }

    /**
     * 使用给定的 Ehcache CacheManager 创建 EhcacheStore.
     *
     * @param cacheManager Ehcache CacheManager
     * @param cacheName    存储验证码的缓存名称
     */
    public EhcacheStore(final net.sf.ehcache.CacheManager cacheManager, final String cacheName) {
        if (!cacheManager.cacheExists(cacheName)) {
            cacheManager.addCache(cacheName);
        }
        cache = cacheManager.getCache(cacheName);

        if (null == cache) {
            throw new IllegalStateException("No cache found/cache can't create for '" + cacheName + '\'');
        }
    }

    /**
     * 使用给定的 Ehcache 来存储验证码.
     *
     * @param cache Ehcache
     */
    public EhcacheStore(final net.sf.ehcache.Cache cache) {
        this.cache = cache;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Captcha get(final String id) {
        final Element el = cache.get(id);
        return null != el ? (Captcha) el.getObjectValue() : null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void put(final String id, final Captcha captcha) {
        cache.put(new Element(id, captcha));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void remove(final String id) {
        cache.remove(id);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public long size() {
        // return cache.getMemoryStoreSize() + cache.getDiskStoreSize();
        return cache.getSize();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    public List<String> keys() {
        return cache.getKeys();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void clear() {
        cache.removeAll();
    }
}
